package demo2;

public class LeetCode1658 {
    public int minOperations(int[] nums, int x) {
        int n = nums.length, sum = 0, len = -1;
        for (int i = 0; i < n; i++) sum += nums[i];
        if (sum < x) return -1;
        int target = sum - x;
        sum = 0;
        for (int left = 0, right = 0; right < n; right++) {
            sum += nums[right];
            while (sum > target) sum -= nums[left++];
            if (sum == target) len = Math.max(len, right - left + 1);
        }
        return len == -1 ? -1 : n - len;
    }
}
